package com.hgzy.meeting.controller;

import com.hgzy.meeting.model.DepartMent;
import com.hgzy.meeting.model.Employee;
import com.hgzy.meeting.service.DepartMentService;
import com.hgzy.meeting.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private DepartMentService departMentService;

    /**
     * 返回到登陆页面
     * @return
     */
    @RequestMapping("/")
    public String login(){
        return "login";
    }

    /**
     * 返回到登陆页面
     * @return
     */
    @RequestMapping("login")
    public String login1(){
        return "login";
    }

    /**
     *  做登录验证
     * @param username
     * @param password
     * @param model
     * @param httpSession
     * @return
     */
    @RequestMapping("/doLogin")
    public String doLogin(String username, String password, Model model, HttpSession httpSession){
        // 查询数据库是否有该用户
        Employee employee= employeeService.doLogin(username,password);
        // 没有该用户 转发到登陆页面
        if(employee==null){
            model.addAttribute("error","用户名或密码错误 登陆失败");
            return "forward:/";
        }else{
            // 或者是待审批的员工 也转发到登陆页面
            if(employee.getStatus()==0){
                model.addAttribute("error","用户待审批");
                return "forward:/";
                // 或者是审批为通过员工 也转发到登陆页面
            }else if (employee.getStatus()==2){
                model.addAttribute("error","用户审批未通过");
                return "forward:/";
            }else {
                // 登陆成功 重定向到主页面
                httpSession.setAttribute("currentUser",employee);
                return "redirect:/notifications";
            }
        }
    }

    /**
     * 注册页面
     * @param model
     * @return
     */
    @RequestMapping("register")
    public String register(Model model){
        // 查询出所有的部门 响应到 页面上
        List<DepartMent> departMentList=departMentService.findAllDeps();
        model.addAttribute("deps",departMentList);
        return "register";
    }

    /**
     * 注册用户
     * @param employee
     * @param model
     * @return
     */
    @RequestMapping("doReg")
    public String doReg(Employee employee,Model model){
        int i=employeeService.doReg(employee);
        if (i==1){
            return "redirect:/";
        }else{
            model.addAttribute("errorDoReg","注册失败 请重新填写");
            model.addAttribute("employee",employee);
            return "forward:/register";
        }


    }


}
